package cn.rengy.web.framework.wxmp.pub.qrcode;

import java.net.URISyntaxException;
import java.time.Duration;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import cn.hutool.core.bean.BeanUtil;
import cn.rengy.lang.ResultEntity;
import cn.rengy.tpa.wxmp.token.AccessToken;
import cn.rengy.tpa.wxmp.user.AccountManager;
import cn.rengy.tpa.wxmp.user.Qrcode;
import cn.rengy.web.framework.id.IdGenerator;
import cn.rengy.web.framework.sql.DbService;
import cn.rengy.web.framework.sys.user.entity.GetQrcodeVO;
import cn.rengy.web.framework.sys.user.entity.QrcodeResult;
import cn.rengy.web.framework.wxmp.pub.project.SysCenterProjectPO;
import cn.rengy.web.framework.wxmp.pub.project.SysCenterProjectService;
import cn.rengy.web.framework.wxmp.token.AccessTokenCacheService;
import cn.rengy.web.framework.wxmp.user.WxUserService;


@Service
public class PubQrcodeService {
	@Autowired
	private DbService dbService;
	
	@Autowired
	private SysCenterProjectService sysCenterProjectService;
	@Autowired
	private AccessTokenCacheService accessTokenCacheService;
	
	@Autowired
	private IdGenerator idGenerator;
	
	private StringRedisTemplate stringRedisTemplate;
	@Autowired
	public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
		this.stringRedisTemplate = stringRedisTemplate;
	}
	private RedisTemplate<Object, Object> redisTemplate;
	@Autowired(required = false)
	public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
	
	/**
	 * 获取临时二维码
	 * @return
	 * @throws URISyntaxException 
	 */
	public ResultEntity<?,QrcodeResult> getTemporaryQrcode(GetQrcodeVO getQrcodeVO){
		Long projectId=getQrcodeVO.getProjectId();
		//1.查询对应appid
		SysCenterProjectPO dcsCenterProjectPO= sysCenterProjectService.getProject(projectId);
		if(dcsCenterProjectPO==null){
			return ResultEntity.fail("项目未找到");
		}
		//2.生成临时二维码
		String appid=dcsCenterProjectPO.getMnpId();
		AccessToken accessToken=accessTokenCacheService.getAccessToken(appid);
		String scene_str=idGenerator.nextId().toString();
		Duration expireTime=Duration.ofMinutes(5);//二维码有效期
		Qrcode qrcode=AccountManager.createQrcodeTemporary(accessToken, scene_str, expireTime);
		qrcode.setTicket(null);
		//3.放入缓存
		ScanQrcodeDTO qrcodeDTO=new ScanQrcodeDTO();
		qrcodeDTO.setAppid(appid);
		qrcodeDTO.setProjectId(dcsCenterProjectPO.getId());
		qrcodeDTO.setScene_str(scene_str);
		qrcodeDTO.setNotifyUrl(getQrcodeVO.getNotifyUrl());
		redisTemplate.opsForValue().set(scene_str, qrcodeDTO, expireTime);
		QrcodeResult qrcodeResult=new QrcodeResult();
		BeanUtil.copyProperties(qrcode, qrcodeResult);
		return ResultEntity.ok(qrcodeResult);
	}
	
	
}
